package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.po.Goods;
import cn.caskm.souvenirshopsystem.domain.po.GoodsCategory;
import cn.caskm.souvenirshopsystem.domain.po.GoodsOrder;
import cn.caskm.souvenirshopsystem.domain.vo.CategoryStatsVO;
import cn.caskm.souvenirshopsystem.domain.vo.DashboardStatsVO;
import cn.caskm.souvenirshopsystem.domain.vo.SalesTrendVO;
import cn.caskm.souvenirshopsystem.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class DashboardServiceImpl implements DashboardService {

    private final GoodsOrderService goodsOrderService;
    private final StudentUserService studentUserService;
    private final GoodsService goodsService;
    private final GoodsCategoryService goodsCategoryService;

    @Override
    public Result<DashboardStatsVO> getDashboardStats() {
        DashboardStatsVO stats = new DashboardStatsVO();
        
        // 获取总订单数
        Long totalOrders = goodsOrderService.count();
        stats.setTotalOrders(totalOrders);
        
        // 获取总用户数
        Long totalUsers = studentUserService.count();
        stats.setTotalUsers(totalUsers);
        
        // 获取商品数量
        Long totalGoods = goodsService.lambdaQuery()
                .eq(Goods::getDeleteStatus, "0")
                .count();
        stats.setTotalGoods(totalGoods);
        
        // 获取总收入（已完成订单的金额总和）
        List<GoodsOrder> completedOrders = goodsOrderService.lambdaQuery()
                .eq(GoodsOrder::getOrderStatus, 3) // 假设3是已完成状态
                .list();
        BigDecimal totalRevenue = completedOrders.stream()
                .map(GoodsOrder::getPrice)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        stats.setTotalRevenue(totalRevenue);
        
        return Result.success(stats);
    }

    @Override
    public Result<SalesTrendVO> getSalesTrend() {
        SalesTrendVO trend = new SalesTrendVO();
        
        // 近7天的日期标签
        List<String> dateLabels = Arrays.asList("周一", "周二", "周三", "周四", "周五", "周六", "周日");
        trend.setDateLabels(dateLabels);
        
        // 计算近7天的销售数据
        LocalDateTime endDate = LocalDateTime.now();
        LocalDateTime startDate = endDate.minusDays(6);
        
        List<BigDecimal> salesData = new ArrayList<>();
        List<Long> orderData = new ArrayList<>();
        
        for (int i = 0; i < 7; i++) {
            LocalDateTime dayStart = startDate.plusDays(i).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime dayEnd = dayStart.withHour(23).withMinute(59).withSecond(59);
            
            // 查询当天的订单
            List<GoodsOrder> dayOrders = goodsOrderService.lambdaQuery()
                    .eq(GoodsOrder::getOrderStatus, 3) // 已完成订单
                    .between(GoodsOrder::getCreateTime, dayStart, dayEnd)
                    .list();
            
            // 计算当天销售额
            BigDecimal daySales = dayOrders.stream()
                    .map(GoodsOrder::getPrice)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            salesData.add(daySales);
            
            // 计算当天订单数
            orderData.add((long) dayOrders.size());
        }
        
        trend.setSalesData(salesData);
        trend.setOrderData(orderData);
        
        return Result.success(trend);
    }

    @Override
    public Result<CategoryStatsVO> getCategoryStats() {
        CategoryStatsVO categoryStats = new CategoryStatsVO();
        
        // 获取所有分类
        List<GoodsCategory> categories = goodsCategoryService.list();
        
        List<String> categoryNames = new ArrayList<>();
        List<Long> categoryValues = new ArrayList<>();
        List<String> categoryColors = Arrays.asList(
                "#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452"
        );
        
        for (GoodsCategory category : categories) {
            // 统计每个分类下的商品数量
            Long goodsCount = goodsService.lambdaQuery()
                    .eq(Goods::getCategoryId, category.getCategoryId())
                    .eq(Goods::getDeleteStatus, "0")
                    .count();
            
            if (goodsCount > 0) {
                categoryNames.add(category.getCategoryName());
                categoryValues.add(goodsCount);
            }
        }
        
        categoryStats.setCategoryNames(categoryNames);
        categoryStats.setCategoryValues(categoryValues);
        categoryStats.setCategoryColors(categoryColors);
        
        return Result.success(categoryStats);
    }
}
